<?php
/**
 * Created by PhpStorm.
 * User: luoqinghui
 * Date: 2020/7/24
 * Time: 上午17:40
 */

namespace App\Http\Controllers\Api\Home;

use App\Jobs\AddFoods;
use App\Modules\Home\Services\AddressService;
//use App\Modules\Home\Services\AreaService;
use App\Http\Controllers\Controller;
use App\Modules\Home\Services\FoodsCategoriesService;
use App\Modules\Home\Services\FoodsDetailService;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class FoodsController extends Controller
{
    /**
     * @return mixed
     */
    public function getFoodsCategories() {
        $res = FoodsCategoriesService::getAll();
        return response()->success($res);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function getFoodsList(Request $request) {
        $food_name = $request->input('food_name','');
        $cat_id = $request->input('cat_id','');
        if(empty($cat_id)&&empty($food_name)) {
            return response()->error('PARAM_EMPTY');
        }

        if($food_name) {
            $client = new Client();
            $page = $request->input('page',1);
            $link = 'http://food.boohee.com/fb/v1/search?tags=&health_light=&q='.$food_name.'&page='.$page;
            $response = $client->request('get',$link,['header'=>[
                'App-Key'=>'food',
                'App-Version'=>'3.0.2',
                'App-Device'=>'ios',
                'User-Agent'=>'FoodLibrary/3/boohee',
                'Phone-Model'=>'iPhone',
                'Device_Id'=>'a700c098823c4568a938e5984b6dce18',
                'Os-Version'=>'13.6.1',
            ]])->getBody()->getContents();
            $ret = json_decode($response,true);
            //请求到的数据丢给队列，对不存在的数据存库
            $job = (new AddFoods($ret['items']))->onConnection('redis')->onQueue('add_foods');
            dispatch($job);
            $res_data = array('list'=>[],'meta'=>[
                'total'=>$ret['total_pages']*20,'per_page'=>20,'current_page'=>$page,'last_page'=>$ret['total_pages']
            ]);
            foreach ($ret['items'] as $key=>$each) {
                $temp = [
                    'id'=>$each['id'],
                    'code'=>$each['code'],
                    'name'=>$each['name'],
                    'img'=>$each['thumb_image_url'],
                    'origin_id'=>$each['id'],
                    'info'=>json_encode($each)
                ];
                $res_data['list'][] = $temp;
            }

            return response()->success($res_data);
        }

        $res = FoodsDetailService::getListByCats(compact('food_name','cat_id'));
        return response()->pagination($res);
    }
}
























